package com.platform.task.job;

import java.util.ArrayList;
import java.util.List;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.TimeUnit;
/**
 * 定时定量执行操作,父类，需要子类实现doJob方法执行其他操作
 */
public abstract class ScheduleIntoDb<T> implements Runnable{
	@SuppressWarnings("rawtypes")
	public Queue cache = new ConcurrentLinkedQueue();
	private boolean flag = false;
	//时间描述
	private int timeCount = 10;
	private int fullNum = 5000;
	private int oldTimeCount = 10;
	public ScheduleIntoDb() {
	}
	public ScheduleIntoDb(int timeCount,int fullNum) {
		this.oldTimeCount =this.timeCount = timeCount;
		this.fullNum = fullNum;
	}
	@Override
	public void run() {
		dida();
		while(true){
			isFull();
			//条件满足其一，则执行
			if((flag || timeCount<=0)&&(cache.size()>0)){
				System.out.println(Thread.currentThread().getName()+" ====* "+timeCount+" ====* "+cache.size());
				reset();
				List<T> tCache = new ArrayList<T>(cache);
				cache.clear();
				doJob(tCache);
			}
			try {
				//隔2秒 监控一次
				TimeUnit.SECONDS.sleep(5);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
	//复位
	public void reset(){
		flag = false;
		timeCount = oldTimeCount;
	}
	//判断集合大小
	public void isFull(){
		flag =  cache.size()>=fullNum? true: false;
	}
	//定时器
	public void dida(){
		new Thread(new Runnable() {
			@Override
			public void run() {
				while(true){
					timeCount=timeCount-2;
					try {
						TimeUnit.SECONDS.sleep(2);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		}).start();
	}
	public int getDida(){
		return timeCount;
	}
	/**
	 * 子类实现
	 */
	abstract public void doJob(List<T> tCache);
}
